package com.movie2.controller;

import com.movie2.config.MyConstants;
import com.movie2.model.entity.*;
import com.movie2.model.vo.ManagerNewPasswordVo;
import com.movie2.service.*;
import com.movie2.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/api/manager")
@CrossOrigin
@Slf4j
public class ManagerController {
    @Autowired
    ManagerPasswordService managerPasswordService;

    @PostMapping("login")
    public Map<String, Object> managerLogin(@RequestBody ManagerPassword managerPassword) {
        log.info("后台管理系统登录：ManagerController -> managerLogin()");
        Map<String, Object> map = new HashMap<>();
        if (managerPassword.getPassword().equalsIgnoreCase(managerPasswordService.selectByPrimaryKey(1).getPassword())) {
            map.put("success", "ok");
        } else {
            map.put("success", "fail");
        }
        return map;
    }

    @Autowired
    UserService userService;

    @GetMapping("/userList")
    public List<User> getUserList() {
        log.info("后台管理系统用户列表：ManagerController -> getUserList()");
        List<User> userList = userService.selectAllUsers();
        for (User user : userList) {
            user.setAvatar(MyConstants.MY_URL + user.getAvatar());
        }
        return userList;
    }

    @Autowired
    ArrangementService arrangementService;

    @GetMapping("/arrangementList")
    public List<Arrangement> getArrangementList() {
        log.info("后台管理系统排片列表：ManagerController -> getArrangementList()");
        List<Arrangement> arrangementList = arrangementService.selectAllArrangements();
        return arrangementList;
    }

    @Autowired
    OrderService orderService;

    @GetMapping("/orderList")
    public List<Map<String, Object>> getOrderList() {
        log.info("后台管理系统订单列表：ManagerController -> getOrderList()");
        List<Map<String, Object>> maps = new ArrayList<>();
        List<Order> orderList = orderService.selectAllOrders();
        for (Order order : orderList) {
            Map<String, Object> map = new HashMap<>();
            Arrangement arrangement = arrangementService.selectByPrimaryKey(order.getAid());
            map.put("order", order);
            map.put("arrangement", arrangement);
            maps.add(map);
        }
        return maps;
    }


    @PostMapping("/updateUserPassword")
    public Map<String, Object> updateUserPassword(@RequestBody ManagerNewPasswordVo vo) {
        log.info("后台管理系统编辑密码：ManagerController -> updatePassword()");
        Map<String, Object> map = new HashMap<>();
        User result = userService.selectByPrimaryKey(vo.getId());
        String newPassword = MD5Util.md5To32String(vo.getNewPassword(), result.getSalt(), result.getSaltIndex());
        result.setPassword(newPassword);
        int count = userService.updateByPrimaryKeySelective(result);
        if (count == 1) {
            map.put("success", "ok");
            map.put("new", newPassword);
        } else {
            map.put("success", "fail");
        }
        return map;
    }


    @Autowired
    WorkerService workerService;

    @GetMapping("/worker")
    public List<Worker> getAllWorker() {
        log.info("后台管理系统工作人员信息：ManagerController -> getAllWorker()");
        List<Worker> workerList=workerService.selectAllWorkers();
        for (Worker worker : workerList) {
            worker.setAvatar(MyConstants.MY_URL+worker.getAvatar());
        }
        return workerList;
    }

    @PostMapping("/updateWorkerPassword")
    public Map<String, Object> updateWorkerPassword(@RequestBody ManagerNewPasswordVo vo) {
        log.info("后台管理系统编辑密码：ManagerController -> updateWorkerPassword()");
        Map<String, Object> map = new HashMap<>();
        System.out.println(vo);
        Worker result = workerService.selectByPrimaryKey(vo.getId());
        System.out.println(result);
        result.setPassword(vo.getNewPassword());
        int count = workerService.updateByPrimaryKeySelective(result);
        if (count == 1) {
            map.put("success", "ok");
            map.put("new", vo.getNewPassword());
        } else {
            map.put("success", "fail");
        }
        return map;
    }

    @GetMapping("/cancelOrder")
    public Map<String, Object> cancelOrder(@RequestParam("oid") Integer oid) {
        Map<String, Object> map = new HashMap<>();
        Order order = new Order();
        order.setId(oid);
        order.setStatus(3);
        int count = orderService.updateByPrimaryKeySelective(order);
        if (count == 1) {
            map.put("success", "ok");
        } else {
            map.put("success", "fail");
        }
        return map;
    }

    @Autowired
    WorkerEvaluateService workerEvaluateService;

    @GetMapping("/deleteWorker")
    public Map<String, Object> deleteWorker(@RequestParam("wid") Integer wid) {
        Map<String, Object> map = new HashMap<>();
        int count;
        count = workerService.deleteByPrimaryKey(wid);
        WorkerEvaluate workerEvaluate = new WorkerEvaluate();
        workerEvaluate.setWid(wid);
        count = workerEvaluateService.deleteByCondition(workerEvaluate);

        if (count == 1) {
            map.put("success", "ok");
        } else {
            map.put("success", "fail");
        }
        return map;
    }

    @Autowired
    ActivityService activityService;
    @Autowired
    RegistrationService registrationService;

    @GetMapping("/deleteActivity")
    public Map<String, Object> deleteActivity(@RequestParam("aid") Integer aid) {
        Map<String, Object> map = new HashMap<>();
        int count;
        count  = activityService.deleteByPrimaryKey(aid);
        Registration registration=new Registration();
        registration.setAid(aid);
        count= registrationService.deleteByCondition(registration);

        if (count == 1) {
            map.put("success", "ok");
        } else {
            map.put("success", "fail");
        }
        return map;
    }

    @Value("${xhn.avatar.upload}")
    String avatarUploadPath;

    // 修改个人设置
    // 单文件上传
    @PostMapping("/avatar/upload")
    public Map<String, String> avatarUpload(@RequestBody MultipartFile file) throws IOException {
        log.info("头像上传：WorkerController类，upload()");
        Map<String, String> map = new HashMap<>();

        File path = new File(avatarUploadPath);
        if (!path.exists()) {
            path.mkdirs();//文件夹不存在，创建文件夹
        }
        String originalFilename = file.getOriginalFilename();//获得原始的文件名“7.jpg”
        int index = originalFilename.lastIndexOf(".");
        String newName = originalFilename.substring(0, index) + "_" + UUID.randomUUID().toString() + originalFilename.substring(index);
        // 保存文件
        try {
            file.transferTo(new File(avatarUploadPath + newName));//不出现异常，就是文件上传成功
            // 对数据库进行操作（把图片的路径保存到数据库中），varchar/char （建议使用）
            // blob二进制文件类型，把图片的二进制文件直接保存到数据库中，（很少用）
            map.put("message", "文件保存成功");
            map.put("db", "数据库保存成功");
            map.put("name", "/images/avatar/" + newName);
            // return "不出现异常，就是文件上传成功";
        } catch (IOException ioException) {
            map.put("message", "文件保存失败");
            ioException.printStackTrace();//文件上传失败
            // return "出现异常，文件上传失败";
            throw ioException;
        }
        return map;
    }

    @PostMapping("/addWorker")
    public Map<String, Object> addWorker(@RequestBody Worker worker) {
        log.info("修改个人设置：UserController -> updateSet(@RequestBody User user)");
        Map<String, Object> map = new HashMap<>();
        if (worker.getAvatar()==""||worker.getAvatar()==null) {
            worker.setAvatar("/images/avatar/default.png");
        }
        worker.setEntry(1);
        int count = workerService.insert(worker);
        if (count == 1) {
            map.put("success", "ok");
        }
        return map;
    }


}
